package bbqtorrent;

import interfacegraphique.FenetrePrincipale;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.net.URLEncoder;
import java.util.ArrayList;

import java.util.Arrays;
import javax.swing.table.DefaultTableModel;

import tools.FileManager;
import tools.Format;

public class TorrentManager {	
	private ArrayList<Torrent> torrents;

	public TorrentManager() {
		this.torrents = new ArrayList<Torrent>();
	}

	private Torrent parseTorrent(FileManager fileManager) throws IOException, InvalidBEncodingException {
		Bdecoder bdecoder = new Bdecoder((InputStream) fileManager.getByteArrayInputStream());
		bdecoder.set_special_map_name("info");		
		BeValue result = bdecoder.bdecode();			
		byte[] hashInfo = bdecoder.get_special_map_digest();


		//System.out.println(URLEncoder.encode(new String(hashInfo, "utf-8"), "utf-8"));
		try {
			System.out.println(Format.encodeURL(Format.byteArray2Hex(hashInfo)));
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		Torrent torrent = new Torrent();		
		torrent.load(result);
		torrent.setHashInfo(hashInfo);

		this.torrents.add(torrent);

		return torrent;
	}

	public Torrent addTorrent(String path) throws InvalidBEncodingException, IOException {
		FileManager fileManager = new FileManager(path);
		return this.parseTorrent(fileManager);		
	}

	public Torrent addTorrent(File file) throws InvalidBEncodingException, IOException {
		FileManager fileManager = new FileManager(file);
		return this.parseTorrent(fileManager);		
	}

	public Torrent find(String name) {
		int i = 0;

		while(i < this.torrents.size()){        	
			if (this.torrents.get(i).getName().equals(name)) {
				return torrents.get(i);
			}

			i++;
		}

		return new Torrent();
	}

	public ArrayList<Torrent> getTorrents() {
		return torrents;
	}

	public Torrent getTorrent(byte[] hash) {

		for (int i =0;i<this.torrents.size();i++) {

			if(Arrays.equals(this.torrents.get(i).getHashInfo(),hash)){

				return this.torrents.get(i);
			}

		}

		return null;

	}

}
